﻿using System.Collections.Generic;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using MyCompany.WebCrawler.Domain;
using MyCompany.WebCrawler.Repositories;
using MyCompany.WebCrawler.Tasks;

namespace MyCompany.WebCrawler.Test.Domain.CrawlerTests.Given_Environment
{
    [TestClass]
    public class When_LoadAllLinksFromUrl : Context
    {
        private const string url = "http://google.com/ads";
        private string result = "";
        private string database = "";
        private Crawler crawler;

        public override void Arrange()
        {
            var fetcher = new Mock<WebCrawler.Domain.UiFetcher>();
            fetcher.Setup(f => f.Show(It.IsAny<string>())).Callback<string>(u => result += u);

            var page = string.Format("<html><a href=\"{0}\">Ads</a></html>", url);
            var downloader = new Mock<Downloader>();
            downloader.Setup(d => d.DownloadString("http://google.com")).Returns(page);

            var repository = new Mock<Repository>();
            repository.Setup(r => r.Save(It.IsAny<string>())).Callback<string>(u => database += u);
            repository.Setup(r => r.Load()).Returns(new List<Url>() {new Url() {Path = "http://google.com/ads"}});

            var factory = new TasksFactory(downloader.Object, fetcher.Object, repository.Object);
            crawler = new Crawler(repository.Object, factory, new ThreadManager(repository.Object));
        }

        public override void Act()
        {
            crawler.Run("http://google.com");
        }

        [TestMethod]
        public void Then_LinkIsShown()
        {
            result.Should().Be(url);
        }
        
        [TestMethod]
        public void Then_LinkInDatabase()
        {
            database.Should().Be(url);
        }
    }
}